# -*- coding: utf-8 -*- 
# @Time : 2023/11/22 14:23 
# @Author : YangGuangjian
# @File : conftest.py

from json import JSONDecodeError
from jsonpath_ng import parse
import pytest
import yaml
import json
from jsonpath import jsonpath
from utils.api_client import APIClient
from utils.logger import get_logger

@pytest.fixture(scope="session")
def api_client():
    return APIClient()

@pytest.fixture(scope="session")
def logger():
    return get_logger("api_test")

# 使用 argparse 模块的 addoption 方法为 pytest 添加了一个自定义的命令行选项 --env。这个选项允许你在运行 pytest 时通过命令行指定一个环境参数。
def pytest_addoption(parser):
    parser.addoption("--env", action="store", default="test", help="Specify the test environment")

@pytest.fixture(scope="session")
def test_environment(request):
    return request.config.getoption("--env")

# 根据环境获取对应的host地址
@pytest.fixture(scope="session")
def host(test_environment):
    with open(r"./configs/env.yaml", "r") as file:
        host = yaml.safe_load(file)
    return host["environments"][test_environment]["api_url"]


#  pytest 的 hook 函数，它在每个测试用例运行之前被调用。它的作用是在测试用例运行之前，为 API 测试准备一些共享的资源。
def pytest_runtest_setup(item):
    if "api" in item.keywords and "test_environment" in item.fixturenames:
        api_client = APIClient()
        item.parent._api_client = api_client
        item.parent._logger = get_logger("api_test")

@pytest.fixture(scope="session")
def load_test_case():
    def _load_test_case(file_path):
        with open(file_path, "r") as file:
            test_data = yaml.safe_load(file)
        return test_data
    return _load_test_case

# 此fixtrue用于根据JPath提起Json数据中的参数
@pytest.fixture(scope="session")
def save_mid_vars():
    def _save_mid_vars(data: dict, j_path: str):
        if isinstance(data, dict):
            contents = [match.value for match in parse(j_path).find(data)]
            return contents
        else:
            try:
                data_dict = json.loads(data)
                contents = [match.value for match in parse(j_path).find(data_dict)]
                return contents
            except JSONDecodeError:
                return None

    return _save_mid_vars